<template>
  <el-dialog
    :visible.sync="visible"
    :close-on-click-modal="false"
    top="30px"
    width="800px"
    :title="`${!this.customerRelatedId ? '新增' : '修改'}经营主体`"
    :before-close="beforeClose"
  >
    <form
      class="ml-3"
      ref="form"
      :class="{ 'was-validated': wasValidated }"
      v-loading="saveLoading"
      novalidate
    >
      <div class="form-group row" v-if="projectType === 2">
        <label for="org_class" class="col-sm-2 col-form-label">
          <span class="text-danger">*</span>
          所属坝区
        </label>
        <div class="col-sm-10">
          <select-dam
            class="form-control-ml"
            @select="setProjectTypeName"
            v-model="editCustomerData.project_type_id"
          ></select-dam>
        </div>
      </div>
      <div class="form-group row" v-else-if="projectType === 3">
        <label for="org_class" class="col-sm-2 col-form-label">
          <span class="text-danger">*</span>
          产业包选择
        </label>
        <div class="col-sm-10">
          <select-credit-goods
            class="form-control-ml"
            @select="setProjectTypeName"
            v-model="editCustomerData.project_type_id"
          ></select-credit-goods>
        </div>
      </div>
      <div class="form-group row">
        <label class="col-sm-2 col-form-label">企业名称</label>
        <div class="col-sm-10">
          <div class="form-control-ml">
            <el-autocomplete
              class="w-100"
              popper-class="customer-autocomplete"
              value-key="customer_name"
              v-model="editCustomerData.customer_name"
              :fetch-suggestions="throttleGetData"
              @input="clearId"
              placeholder="请输入企业名称"
              @select="handleSelectFarm"
            >
              <template slot-scope="props">
                <div class="farm-name">{{ props.item.customer_name }}</div>
                <small class="text-muted">{{ props.item.address_detail }}</small>
              </template>
            </el-autocomplete>
          </div>
          <div class="invalid-feedback">请输入企业名称</div>
        </div>
      </div>

      <div class="form-group row">
        <label for="address_code" class="col-sm-2 col-form-label">
          <span class="text-danger">*</span>
          经营地址
        </label>
        <div class="col-sm-10">
          <div class="d-flex">
            <select-address
              id="address_code"
              :placeholder="addressHolder"
              class="form-control-ml mr-2"
              v-model="editCustomerData.address_code"
              auto-top
              ref="address"
            ></select-address>
          </div>
        </div>
      </div>
      <div class="form-group row">
        <label for="address_detail" class="col-sm-2 col-form-label">详细地址</label>
        <div class="col-sm-10">
          <input
            type="text"
            class="form-control form-control-ml"
            v-model="editCustomerData.address_detail"
            id="address_detail"
            placeholder="请输入详细地址"
          />
        </div>
      </div>

      <div class="form-group">
        <div class="row">
          <label for="org_class" class="col-sm-2 col-form-label">
            <span class="text-danger">*</span>
            组织类型
          </label>
          <div class="col-sm-10">
            <select-farm-org v-model="editCustomerData.org_class"></select-farm-org>
          </div>
        </div>
      </div>
      <div class="form-group row">
        <label for="corp_name" class="col-sm-2 col-form-label">
          <span class="text-danger">*</span>
          经营者姓名
        </label>
        <div class="col-sm-10">
          <input
            type="text"
            class="form-control form-control-ml"
            v-model="editCustomerData.corp_name"
            id="corp_name"
            placeholder="请输入经营者姓名"
            required
          />
          <div class="invalid-feedback">请输入经营者姓名</div>
        </div>
      </div>
      <div class="form-group row">
        <label for="lender_idcard" class="col-sm-2 col-form-label">
          <span class="text-danger">*</span>
          经营者身份证
        </label>
        <div class="col-sm-10">
          <input
            type="text"
            @input="checkIdCardNo"
            class="form-control form-control-ml"
            v-model="editCustomerData.lender_idcard"
            id="lender_idcard"
            placeholder="请输入经营者身份证"
            required
          />
          <div class="invalid-feedback">请输入正确的经营者身份证</div>
        </div>
      </div>
      <div class="form-group row">
        <label for="mobile_no" class="col-sm-2 col-form-label">
          <span class="text-danger">*</span>
          联系电话
        </label>
        <div class="col-sm-10">
          <input
            type="text"
            class="form-control form-control-ml"
            v-model="editCustomerData.mobile_no"
            id="mobile_no"
            placeholder="请输入联系电话"
            pattern="^1[345678][0-9]{9}$"
            required
          />
          <div class="invalid-feedback">请输入正确的手机号</div>
        </div>
      </div>
      <div class="form-group row">
        <label for="register_no" class="col-sm-2 col-form-label">统一社会信用代码</label>
        <div class="col-sm-10">
          <div class="input-group">
            <input
              type="text"
              class="form-control form-control-ml"
              v-model="editCustomerData.register_no"
              id="register_no"
              placeholder="请输入统一社会信用代码"
            />
            <div class="input-group-append">
              <el-button class="input-group-text" type="info" @click="linkto">
                工商公示信息
              </el-button>
            </div>
            <div class="invalid-feedback">请输入统一社会信用代码</div>
          </div>
        </div>
      </div>
      <div class="form-group row">
        <label for="apply_funds" class="col-sm-2 col-form-label">
          <span class="text-danger">*</span>
          申请金额
        </label>
        <div class="col-sm-10">
          <div class="input-group">
            <input
              type="number"
              class="form-control form-control-ml"
              v-model="editCustomerData.apply_funds"
              id="apply_funds"
              placeholder="请输入金额"
              min="0"
              step="0.0001"
              required
            />
            <div class="input-group-append"><span class="input-group-text">万元</span></div>
            <div class="invalid-feedback">请输入正确的金额，最多4位小数</div>
          </div>
        </div>
      </div>
      <div class="form-group row">
        <label for="load_years" class="col-sm-2 col-form-label">
          <span class="text-danger">*</span>
          贷款期限
        </label>
        <div class="col-sm-10">
          <div class="input-group">
            <input
              type="number"
              class="form-control form-control-ml"
              v-model="editCustomerData.load_years"
              id="load_years"
              placeholder="请输入贷款期限"
              min="0"
              step="1"
              required
            />
            <div class="input-group-append"><span class="input-group-text">年</span></div>
            <div class="invalid-feedback">请输入正确的贷款期限，只能输入整数</div>
          </div>
        </div>
      </div>

      <fieldset class="form-group" v-if="projectType === 2">
        <div class="row">
          <legend class="col-form-label col-sm-2 pt-0">是否牵头企业</legend>
          <div class="col-sm-10">
            <c-radio-group
              :options="enumISNom"
              v-model="editCustomerData.is_lead_com"
            ></c-radio-group>
          </div>
        </div>
      </fieldset>

      <fieldset class="form-group">
        <div class="row">
          <legend class="col-form-label col-sm-2 pt-0">是否扶贫项目</legend>
          <div class="col-sm-10">
            <c-radio-group
              :options="enumISNom"
              v-model="editCustomerData.is_poverty_project"
            ></c-radio-group>
          </div>
        </div>
      </fieldset>

      <div class="form-group row">
        <label for="poverty_households" class="col-sm-2 col-form-label">
          <span class="text-danger">*</span>
          带动农户
        </label>
        <div class="col-sm-10">
          <div class="input-group">
            <input
              type="number"
              class="form-control form-control-ml"
              v-model="editCustomerData.poverty_households"
              id="poverty_households"
              placeholder="请输入带动农户数"
              min="0"
              step="1"
              required
            />
            <div class="input-group-append"><span class="input-group-text">人</span></div>
            <div class="invalid-feedback">请输入带动农户数，只能输入整数</div>
          </div>
        </div>
      </div>
      <div class="form-group row">
        <label for="funds_use_dir" class="col-sm-2 col-form-label">申请资金用途</label>
        <div class="col-sm-10">
          <input
            type="text"
            class="form-control form-control-ml"
            id="funds_use_dir"
            v-model="editCustomerData.funds_use_dir"
            placeholder="请输入申请资金用途"
          />
        </div>
      </div>

      <div class="form-group row">
        <label for="mobile_no" class="col-sm-2 col-form-label">
          <span class="text-danger">*</span>
          主营产业
        </label>
        <div class="col-sm-10">
          <c-select
            :options="enumIndustryType"
            ref="business"
            placeholder="请选择主营产业"
            class="form-control-ml"
            v-model="editCustomerData.main_business"
          ></c-select>
          <div class="invalid-feedback">请选择主营产业</div>
        </div>
      </div>

      <fieldset class="form-group">
        <div class="row">
          <legend class="col-form-label col-sm-2 pt-0">经营范围</legend>
          <div class="col-sm-10">
            <input
              type="text"
              class="form-control form-control-ml"
              id="business_scope"
              v-model="editCustomerData.business_scope"
              placeholder="请输入经营范围"
            />
          </div>
        </div>
      </fieldset>

      <div class="form-group row">
        <div class="col-sm-2"></div>
        <div class="col-sm-10">
          <el-button type="primary" :loading="saveLoading" class="btn-long" @click="onSubmit">
            保存
          </el-button>
        </div>
      </div>
    </form>
  </el-dialog>
</template>
<script>
import { mapGetters } from 'vuex'
import { idCardValidate, throttle } from '@vimi/utils-tool'
// import { createFarm, putFarm } from '@/common/api/industrial'
import { enumCustomerSource } from '@/credit/plugins/enum'
import SelectFarmOrg from '@/components/select/SelectFarmOrg'
import SelectDam from '@/gov/components/select/SelectDam'
import SelectCreditGoods from '@/gov/components/select/SelectCreditGoods'
import SelectAddress from '@/components/select/SelectAddress'
import { PATTERN_ID_CARD } from '@/common/plugins/constant'
import { enumISNom } from '@/gov/plugins/enum'
import { enumIndustryType, enumParentMainBusiness } from '@/bank/plugins/enum'
export default {
  components: {
    SelectFarmOrg,
    SelectAddress,
    SelectDam,
    SelectCreditGoods,
  },
  props: {
    visible: Boolean,
    customerData: Object,
    customerId: String,
    customerRelatedId: String,
    projectType: {
      type: Number,
      default: 1,
    },
  },
  data() {
    return {
      enumIndustryType,
      enumParentMainBusiness,
      patternIdCard: PATTERN_ID_CARD,
      enumISNom,
      enumCustomerSource,
      wasValidated: false,
      type: false, // 编辑
      editCustomerData: {
        poverty_households: '',
        project_type_id: '',
        customer_id: '',
        project_type_name: '',
        customer_name: '',
        corp_name: '',
        mobile_no: '',
        address_code: '',
        address_detail: '',
        business_scope: '',
        is_lead_com: '0',
        register_no: '',
        org_class: '',
        funds_use_dir: '',
        apply_funds: '',
        load_years: '',
        invest_total: '',
        invest_self: '',
        last_year_income: '',
        last_year_profit: '',
        current_year_income: '',
        next_year_income: '',
        en_debt: '',
        personal_debt: '',
        lender_idcard: '',
        main_business: '',
        is_poverty_project: '0',
      },
      initCustomerData: {},
      saveLoading: false,
      tableName: 'customer_related',
      customerLoading: false,
      customerParams: {
        index: 1,
        size: 30,
        customer_name: '',
      },

      loading: false,
      productLoading: false,
      deleteIndex: -1,
      deleteDialogVisible: false,
      addressDetail: '',
    }
  },
  computed: {
    ...mapGetters(['org', 'user']),
    addressHolder() {
      const reg = new RegExp(this.editCustomerData.address_detail || '')
      return (this.addressDetail || '').replace(reg, '') || this.addressDetail || '请选择地址'
    },
  },
  watch: {
    visible(val) {
      if (val) {
        this.getCustomerData()
      }
    },
  },
  created() {
    this.customerParams.address_code = this.$utils.getAddressCode()
    this.initCustomerData = { ...this.editCustomerData }
  },
  mounted() {},
  methods: {
    throttleGetData: throttle(500, function (queryString, cb) {
      this.getCustomer(queryString, cb)
    }),

    clearId() {
      if (this.customerRelatedId) {
        return
      }
      this.editCustomerData.customer_id = ''
    },
    checkIdCardNo(e) {
      const target = e.target
      const { value } = target
      this.changeCardNo(target, value)
    },
    changeCardNo(target, value) {
      if (idCardValidate(value)) {
        target.setCustomValidity('')
      } else {
        target.setCustomValidity('身份证格式错误！')
      }
    },
    beforeClose() {
      this.customerList = []
      this.wasValidated = false
      this.editCustomerData = { ...this.initCustomerData }
      this.$emit('update:visible', false)
    },

    async getCustomerData() {
      // 是否有编辑信息
      if (this.customerData && this.customerData.customer_id) {
        this.setCustomerData(this.customerData)
      } else if (this.customerId || this.customerRelatedId) {
        // 通过传入的customerId获取到客户信息
        const params = {}
        if (this.customerId) {
          params['customer_id.eq'] = this.customerId
        }
        if (this.customerRelatedId) {
          params['customer_related_id.eq'] = this.customerRelatedId
        }
        this.saveLoading = true
        const [res, err] = await this.$utils.promise(
          this.$api.getData('credit', 'customer_related', params)
        )
        this.saveLoading = false
        if (err) {
          return this.$message.error('获取客户信息失败！')
        }
        const data = (res && res.data && res.data.length && res.data[0]) || {}
        this.addressDetail = data.address || ''
        this.setCustomerData(data)
      } else {
        this.type = true // 新增
      }
    },

    setCustomerData(customer) {
      if (!customer) {
        customer = { ...this.initCustomerData }
      }
      Object.keys(this.editCustomerData).forEach(key => {
        this.editCustomerData[key] = customer[key] || this.initCustomerData[key]
      })
      this.changeCardNo(
        document.getElementById('lender_idcard'),
        this.editCustomerData.lender_idcard
      )
      this.editCustomerData.customer_id = customer.customer_id
    },

    async getCustomer(queryString = '', cb) {
      queryString = queryString.trim()
      let data = []

      if (this.customerParams.customer_name === queryString) {
        cb(data)
        return
      }

      this.customerParams.customer_name = queryString
      this.customerLoading = true
      const [res] = await this.$utils.promise(
        this.$api.getData('credit', 'datum_customer_info_warehouse', this.customerParams)
      )
      this.customerLoading = false

      if (res && res.data) {
        data = res.data.data || []
      }

      cb(data)
    },

    handleSelectFarm(customer) {
      this.setCustomerData(customer)
    },

    onDeleteProduct(index) {
      this.deleteIndex = index
      this.deleteDialogVisible = true
    },

    onNext() {
      // 判断输入与列表匹配
      if (!this.customerParams.customer_name) {
        return this.$message.warning('请先填写或选择客户！')
      }
      let customer = null
      for (const item of this.customerList) {
        if (item.customer_name === this.customerParams.customer_name) {
          customer = item
          break
        }
      }
      this.onSelectCustomer(customer)
    },
    setProjectTypeName(name) {
      this.editCustomerData.project_type_name = name
    },
    onSubmit() {
      this.wasValidated = true
      const form = this.$refs.form
      if (!form.checkValidity()) {
        return
      }
      if (!this.editCustomerData.main_business) {
        return this.$message.warning('请选择主营产业')
      }
      if (!this.editCustomerData.project_type_id) {
        if (this.projectType === 2) {
          return this.$message.warning('请选择坝区')
        }
        if (this.projectType === 3) {
          return this.$message.warning('请选择产业包')
        }
      }

      // 只有乡镇农担可以推荐，所以必须选择到乡镇
      const addressCode = this.editCustomerData.address_code
      if (!addressCode || +addressCode.replace(/^\d{6}/, '') === 0) {
        return this.$message.error('请选择乡镇及以下的经营地址')
      }

      const data = {
        submit_type: 1,
        customer_name: this.editCustomerData.customer_name,
        corp_name: this.editCustomerData.corp_name,
        mobile_no: this.editCustomerData.mobile_no,
        address_code: this.editCustomerData.address_code,
        address_detail: this.editCustomerData.address_detail,
        // farmType: this.editCustomerData.farm_type,
        register_no: this.editCustomerData.register_no,
        org_class: this.editCustomerData.org_class,
        lender_idcard: this.editCustomerData.lender_idcard,
        project_type: this.projectType,
        poverty_households: this.editCustomerData.poverty_households,
        business_scope: this.editCustomerData.business_scope,
        main_business: this.editCustomerData.main_business,
        parent_main_business: enumParentMainBusiness[this.editCustomerData.main_business] || '',
        is_poverty_project: this.editCustomerData.is_poverty_project,
        apply_funds: this.editCustomerData.apply_funds,
        load_years: this.editCustomerData.load_years,
        funds_use_dir: this.editCustomerData.funds_use_dir,
      }

      if (this.projectType === 2) {
        data.is_lead_com = this.editCustomerData.is_lead_com
        data.project_type_id = this.editCustomerData.project_type_id
        data.project_type_name = this.editCustomerData.project_type_name
      } else if (this.projectType === 3) {
        data.project_type_id = this.editCustomerData.project_type_id
        data.project_type_name = this.editCustomerData.project_type_name
      }
      if (this.editCustomerData.customer_id) {
        data.customer_id = this.editCustomerData.customer_id
      } else {
        data.submit_client_id = this.$store.getters.clientId
        data.submit_client_name = this.$store.getters.org.orgName
        data.submit_person_name = this.$store.getters.user.realName
      }
      if (!this.customerRelatedId) {
        this.addFarm(data)
      } else {
        this.updateFarm(data)
      }
    },

    updateFarm(data) {
      this.saveLoading = true
      this.$api
        .updateData(this.$serviceName, this.tableName, this.customerRelatedId, data)
        .then(() => {
          this.$message.success('修改客户成功！')
          this.getCustomerData()
          this.beforeClose()
          this.$emit('success', true)
        })
        .catch(err => {
          if (err) {
            const errStr = typeof err.data === 'string' ? err.data : '修改客户失败，请重试！'
            return this.$message.error(`${errStr}`)
          }
        })
        .finally(() => {
          this.saveLoading = false
        })
    },
    addFarm(data) {
      this.saveLoading = true
      this.$api
        .addData(this.$serviceName, this.tableName, data)
        .then(() => {
          this.$message.success('添加客户成功！')
          this.beforeClose()
          this.$emit('success', true)
        })
        .catch(err => {
          if (err) {
            const errStr = typeof err.data === 'string' ? err.data : '添加客户失败，请重试！'
            return this.$message.error(`${errStr}`)
          }
        })
        .finally(() => {
          this.saveLoading = false
        })
    },

    linkto() {
      window.open('http://www.gsxt.gov.cn/index.html')
    },
  },
}
</script>
<style scoped lang="scss">
.footer-view {
  margin-top: 2rem;
  margin-bottom: 2rem;
  margin-left: 1rem;
}

.btn-long {
  min-width: 100px;
}
</style>
